//
//  WeatherViewController.m
//  SnailPost
//
//  Created by 抠泥ser on 16/3/22.
//  Copyright © 2016年 抠泥ser. All rights reserved.
//

#import "WeatherViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "WeatherModel.h"

#import <MapKit/MapKit.h>

@interface WeatherViewController ()<CLLocationManagerDelegate>

@property (nonatomic,retain) CLLocationManager *locationManager;
@property (nonatomic,retain) CLLocation *location;
@property (nonatomic,retain) NSString *city;/**< 城市属性 */

@property (nonatomic, retain) UIImageView *beijing;
@property (nonatomic, retain) NSMutableArray *threeDayData;/**< 三天的数据 */
@property (nonatomic, retain) WeatherModel *m;/**< 今天的数据 */

@end

@implementation WeatherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.navigationController.navigationBar.alpha = 0.2;
    
   // self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tianqi111.jpg"]];
    self.view.backgroundColor = [UIColor whiteColor];
    self.beijing = [[UIImageView alloc] initWithFrame:self.view.bounds];
    _beijing.image = [UIImage imageNamed:@"tianqi111.jpg"];
    [self.view addSubview:_beijing];
    
    
    // 定位
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
        return;
    }
    //请求用户授权
    [_locationManager requestWhenInUseAuthorization];
    
    [self dingwei];
    

    
    
}

#pragma mark - 获取城市
- (void)getCity
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:_location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0)
            
        {
            
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            
            //将获得的所有信息显示到label上
            
            //            NSLog(@"%@",placemark.name);
            //            UILabel *label = [self.view viewWithTag:8888];
            //            label.text = placemark.name;
            //            label.numberOfLines = 0;
            //            [label sizeToFit];
            
            //获取城市
            
            NSString *city = placemark.locality;
        
            self.navigationItem.title = city;
            
            self.city = [city substringToIndex:[city length] - 1];
            
            //self.city = @"大连";
            
            [self dataHander];
            
            
           // NSLog(@"%@", city);
            
            if (!city) {
                
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                
                city = placemark.administrativeArea;
                
            }
            
            //            UILabel *label = [self.view viewWithTag:8888];
            //            label.text = city;
            
        }
        
        else if (error == nil && [placemarks count] == 0)
            
        {
            
            NSLog(@"No results were returned.");
            
        }
        
        else if (error != nil)
            
        {
            
            NSLog(@"An error occurred = %@", error);
            
        }
        
    }];
    
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    
    [_locationManager stopUpdatingLocation];
}

#pragma mark - 网络请求
- (void)dataHander
{
    // 转码
    NSString *urlStr = [_city stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:_city]];
    
    NSString *url = [NSString stringWithFormat:@"http://app.tianqi.com/index.php?a=json15&area=%@&c=app&city=%@&showid=3&token=&type=1",urlStr,urlStr];
    
    [LMTAFNetwork getUrl:url body:nil response:LMTJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        
        NSLog(@"%@", resposeObject);
        
        self.threeDayData = [NSMutableArray array];
        //获取今明后数据
        for (NSInteger i = 1; i<4; i++) {
            WeatherModel *m = [[WeatherModel alloc]init];
            [m setValuesForKeysWithDictionary:resposeObject[@"resultvalue"][i]];
            [self.threeDayData addObject:m];
            
            //获取当天数据
            if ([m.week isEqualToString:@"今天"]) {
                self.m = m;
            }
        }
        
        [self creatPage];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}
#pragma mark - 创建页面
- (void)creatPage
{
    
    //显示视图底层
    UIView *downView = [[UIView alloc]initWithFrame:CGRectMake(0, 110*PW, WIDTH, 300*PH)];
    downView.backgroundColor = [UIColor clearColor];
    [_beijing addSubview:downView];
    
    //天气图片
    UIImageView *weatherImg = [[UIImageView alloc]initWithFrame:CGRectMake(15*PW, 15*PH, 50*PW, 50*PH)];
    [downView addSubview:weatherImg];
    
    
    //文字天气
    UILabel *weatherLabel = [[UILabel alloc]initWithFrame:CGRectMake(70*PW, 25*PH, 50*PW, 30*PH)];
    
    //        NSString *str = [self.toDayModel.weather s:1];
    weatherLabel.text = self.m.weaday;
    
    weatherLabel.font = [UIFont systemFontOfSize:20];
    weatherLabel.textColor = [UIColor whiteColor];
    //        weatherLabel.backgroundColor = [UIColor greenColor];
    [downView addSubview:weatherLabel];
    
    [WeatherViewController weatherPicker:weatherImg str:weatherLabel.text];
    
    //文字温度
    UILabel *temperaturelabel = [[UILabel alloc]initWithFrame:CGRectMake(15*PW, 75*PH, 200*PW, 60*PH)];
    temperaturelabel.text = [NSString stringWithFormat:@"%@℃",self.m.stemp];
    temperaturelabel.font = [UIFont systemFontOfSize:55];
    temperaturelabel.textColor = [UIColor whiteColor];
    //        temperaturelabel.backgroundColor = [UIColor purpleColor];
    [downView addSubview:temperaturelabel];
    
    //最低和最高温度
    UILabel *upAndDownLabel = [[UILabel alloc]initWithFrame:CGRectMake(15*PW, 160*PH, 90*PW, 20*PH)];
    upAndDownLabel.text = [NSString stringWithFormat:@"%@/%@",self.m.ltemp,self.m.htemp];
    upAndDownLabel.textColor = [UIColor whiteColor];
    //        upAndDownLabel.backgroundColor = [UIColor orangeColor];
    [downView addSubview:upAndDownLabel];
    
    //湿度等等
    UILabel *humidityLabel = [[UILabel alloc]initWithFrame:CGRectMake(15*PW, 190*PH, 170*PW, 20*PH)];
    humidityLabel.text = [NSString stringWithFormat:@"%@ %@ 湿度 %@",self.m.WD,self.m.WS,self.m.SD];
    humidityLabel.font = [UIFont systemFontOfSize:15];
    humidityLabel.textColor = [UIColor whiteColor];
    //        humidityLabel.backgroundColor = [UIColor yellowColor];
    [downView addSubview:humidityLabel];
    
//    //预警
//    UIImageView *warningView = [[UIImageView alloc]initWithFrame:CGRectMake(15*PW, 225*PH, 60*PW, 50*PH)];
//    [warningView sd_setImageWithURL:[NSURL URLWithString:self.m.alarmnews.firstObject[@"img"]]];
//    //        warningView.backgroundColor = [UIColor grayColor];
//    [downView addSubview:warningView];
    
    //PM2.5
    UIView *pmImg = [[UIView alloc]initWithFrame:CGRectMake(300*PW, 15*PH, 65*PW, 30*PH)];
    //        pmImg.backgroundColor = [UIColor redColor];
    [downView addSubview:pmImg];
    
    //pm文字状况
    UILabel *pmLabel = [[UILabel alloc]initWithFrame:CGRectMake(300*PW, 45*PH, 65*PW, 25*PH)];
    pmLabel.text = [self.m.air[@"col"] firstObject];
    
    pmLabel.textColor = [UIColor whiteColor];
    //                pmLabel.backgroundColor = [UIColor blueColor];
    pmLabel.font = [UIFont systemFontOfSize:13];
    pmLabel.textAlignment = NSTextAlignmentCenter;
    [downView addSubview:pmLabel];
    
    
    //pm数字阴影
//    UIView *pmNumberView = [[UIView alloc]initWithFrame:CGRectMake(290*PW, 75*PH, 85*PW, 25*PH)];
//    pmNumberView.backgroundColor = [UIColor blackColor];
//    pmNumberView.alpha = 0.1;
//    [downView addSubview:pmNumberView];
    
    //pm数字
//    UILabel *pmNumberLabel = [[UILabel alloc]initWithFrame:CGRectMake(290*PW, 75*PH, 85*PW, 25*PH)];
//    pmNumberLabel.text = [NSString stringWithFormat:@"PM2.5|%@",self.m.air[@"pm"]];
//    pmNumberLabel.textColor = [UIColor whiteColor];
//    pmNumberLabel.font = [UIFont systemFontOfSize:16];
//    pmNumberLabel.textAlignment = NSTextAlignmentCenter;
//    [downView addSubview:pmNumberLabel];
    
    
    //今天 明天 星期一 阴影
    UIView *dayToDay = [[UIView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height -80, WIDTH, 80)];
    dayToDay.backgroundColor = [UIColor blackColor];
    dayToDay.alpha = 0.3;
    [self.beijing addSubview:dayToDay];
    NSArray *arr = [NSArray arrayWithObjects:@"今天",@"明天",@"后天", nil];
    
    for (NSInteger i = 1; i<4; i++) {
        WeatherModel *m = self.threeDayData[i-1];
        //日期
        UILabel *labelDay = [[UILabel alloc]initWithFrame:CGRectMake(54*PW*i+(i-1)*60*PW, 590*PH, 40*PW, 20*PH)];
        labelDay.font = [UIFont systemFontOfSize:15];
        labelDay.text = arr[i-1];
        labelDay.textColor = [UIColor whiteColor];
        //            labelDay.backgroundColor = [UIColor redColor];
        labelDay.textAlignment = NSTextAlignmentCenter;
        [_beijing addSubview:labelDay];
        
        //天气图片
        UIImageView *tianqiImg = [[UIImageView alloc]initWithFrame:CGRectMake(40*PW*i+(i-1)*60*PW, 25*PH, 32*PW, 32*PH)];
        tianqiImg.center = CGPointMake(labelDay.center.x-labelDay.frame.size.width/2,labelDay.center.y+labelDay.frame.size.height/2+16*PH);
        [_beijing addSubview:tianqiImg];
        
        //白天温度
        UILabel *baitianLabel = [[UILabel alloc]initWithFrame:CGRectMake(tianqiImg.frame.origin.x+tianqiImg.frame.size.width,tianqiImg.frame.origin.y, 40*PW, 16*PH)];
        baitianLabel.text = m.htemp;
        //            baitianLabel.backgroundColor = [UIColor blueColor];
        baitianLabel.textColor = [UIColor whiteColor];
        baitianLabel.textAlignment = NSTextAlignmentCenter;
        [_beijing addSubview:baitianLabel];
        
        //晚上温度
        UILabel *nightLabel = [[UILabel alloc]initWithFrame:CGRectMake(baitianLabel.frame.origin.x, baitianLabel.frame.origin.y+baitianLabel.frame.size.height, baitianLabel.frame.size.width, baitianLabel.frame.size.height)];
        nightLabel.text = m.ltemp;
        //            nightLabel.backgroundColor = [UIColor purpleColor];
        nightLabel.textColor = [UIColor whiteColor];
        nightLabel.textAlignment = NSTextAlignmentCenter;
        [_beijing addSubview:nightLabel];
        
        //类似多云～小雨这样
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(tianqiImg.frame.origin.x, tianqiImg.frame.origin.y+tianqiImg.frame.size.height, tianqiImg.frame.size.width+baitianLabel.frame.size.width, 20*PH)];
        label.font = [UIFont systemFontOfSize:15];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = m.weather;
        //
        NSArray *arr = [m.weather componentsSeparatedByString:@"~"];
        NSString *str = arr.firstObject;
        //            NSString
        
        label.textColor = [UIColor whiteColor];
        [_beijing addSubview:label];
        
        [WeatherViewController weatherPicker:tianqiImg str:str];
        
    }
}

//天气图片
+(UIView *)weatherPicker:(UIView *)view str:(NSString *)str
{
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, view.frame.size.width, view.frame.size.height)];
    [view addSubview:img];
    if ([str isEqualToString:@"多云"]) {
        img.image = [UIImage imageNamed:@"duoyun.png"];
    }else if ([str isEqualToString:@"阴"]){
        img.image = [UIImage imageNamed:@"yin.png"];
    }else if ([str isEqualToString:@"小雨"]){
        img.image = [UIImage imageNamed:@"xiaoyu.png"];
        
    }else if ([str isEqualToString:@"晴"]){
        img.image = [UIImage imageNamed:@"qing.png"];
        
    }else if ([str isEqualToString:@"阵雨"]){
        img.image = [UIImage imageNamed:@"zhenyu.png"];
    }
    

    return view;
}

#pragma mark - 定位
- (void)dingwei
{
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置过滤器为无
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    // 开始定位
    [_locationManager startUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    
    
    /* 处理定位成功，manager参数表示位置管理器实例；locations为一个数组，是位置变化的集合，它按照时间变化的顺序存放。如果想获得设备的当前位置，只需要访问数组的最后一个元素即可。集合中每个对象类型是CLLocation，它包含以下属性：
     
     coordinate — 坐标。一个封装了经度和纬度的结构体。
     
     altitude — 海拔高度。正数表示在海平面之上，而负数表示在海平面之下。
     
     horizontalAccuracy — 位置的精度(半径)。位置精度通过一个圆表示，实际位置可能位于这个圆内的任何地方。这个圆是由coordinate(坐标)和horizontalAccuracy(半径)共同决定的，horizontalAccuracy的值越大，那么定义的圆就越大，因此位置精度就越低。如果horizontalAccuracy的值为负，则表明coordinate的值无效。
     
     verticalAccuracy — 海拔高度的精度。为正值表示海拔高度的误差为对应的米数；为负表示altitude(海拔高度)的值无效。*/
    
    //获取设备当前位置
    
    
    _location = [locations lastObject]; //取出第一个位置
    
    [self getCity];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
